<?php

namespace app\mall\controller\admin;

use app\mall\model\MallCateAttr as AttrModel;
use think\facade\View;

class MallCateAttr extends Base
{

    public function index()
    {
        $cateId = $this->requireParam('cate_id');
        View::assign('urlSave', $this->urlA('mallCateAttr/save', ['cate_id' => $cateId]));
        // 统计
        $goodsTotal = \app\mall\model\MallGoods::where('cate_id', $cateId)->count();
        $goodsStockTotal = \app\mall\model\MallGoodsStock::where('cate_id', $cateId)->count();
        View::assign('goodsTotal', $goodsTotal);
        View::assign('goodsStockTotal', $goodsStockTotal);

        //配置
        $data = \app\mall\model\MallCateAttr::where('cate_id', $cateId)->select()->toJson();
        View::assign('data', $data);
        return View::fetch('/mallCateAttr/index');
    }

    public function save()
    {
        $cateId = $this->requireParam('cate_id');
        $attr = $this->requirePost('attr');
        $exist = [];
        $rs = false;
        foreach ($attr as $item) {
            $exist[] = $item['name'];
            $info = [];
            if (isset($item['id']) && $item['id']) {
                $info = AttrModel::where('cate_id', $cateId)->find($item['id']);
            }
            if (!$info) {
                $item['cate_id'] = $cateId;
                if(isset($item['id'])){
                    unset($item['id']);
                }
                $info = new AttrModel();
            }
            $item['value'] = implode(' ', $item['value']);
            $rs = $info->save($item) || $rs;
        }
        //删除项目
        $delModel = AttrModel::where('cate_id', $cateId);
        if ($exist) {
            $delModel = $delModel->whereNotIn('name', $exist);
        }
        $rs = $delModel->delete() || $rs;
        return $this->handleResponse($rs);
    }

}